import { NextApiRequest, NextApiResponse } from "next";
import { getApp, getCurrentUser, updateApp } from "@/services";
import { App } from "@/entities/App";

// !!! this config is required
// export const config = {
//     api: {
//         bodyParser: false,
//     },
// };

async function changeStatus(req: NextApiRequest, res: NextApiResponse<APIRes>) {
  const { id: appid } = req.body;
  req.query.appid = appid;

  // only super user or admin of this app can change status
  const appResult = await getApp(req);
  if (!appResult.success) {
    res.status(400).json(appResult);
    return;
  }

  const app = appResult.data as App;

  const curUser = await getCurrentUser(req);
  if (!curUser) {
    res.status(401).json({
      success: false,
      data: {},
      message: "You are not logged in",
    });
    return;
  }

  const isSuperUser = curUser.id === 1;
  // @ts-ignore
  const isAdminUser = app.admin.id === curUser.id;

  if (!isSuperUser && !isAdminUser) {
    res.status(403).json({
      success: false,
      data: {},
      message: "You are not super user or an admin of this app",
    });
    return;
  }

  await updateApp(req, res);
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<APIRes>
) {
  if (req.method === "POST") {
    changeStatus(req, res);
  } else {
    res.status(405).json({
      success: false,
      data: {},
      message: "Method not allowed",
    });
  }
}
